package com.sk.rpcAssistNetty.provideAssist;

import com.sk.rpcAssistNetty.dataManager.ProviderDataManager;
import com.sk.rpcAssistNetty.io.netty.server.NettyServer;
import com.sk.rpcAssistNetty.io.protocol.SerializeProtocol;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;

import java.util.Properties;

/**
 * description：使用netty作为网络io的server端
 *
 * @author 孙文斌
 * @Date: 2021/3/18 10:23
 */
@Slf4j
public class DefaultProviderAstStrategyNetty implements ProviderAssistStrategyInter {

    private ProviderDataManager providerDataManager;

    private SerializeProtocol serializeProtocol;

    private NettyServer nettyServer;

    //    private final String RPC_SERVER_SOCKET_PORT = "rpc.server.socket.port";
    private final String RPC_SERVER_NETTY_PORT = "rpc.server.netty.port";

    public DefaultProviderAstStrategyNetty(ProviderDataManager providerDataManager, SerializeProtocol serializeProtocol) {
        this.providerDataManager = providerDataManager;
        this.serializeProtocol = serializeProtocol;
        //开启注册
        register();
        //启动监听处理请求
        doProcess();
    }

    @Override
    public void register() {
        providerDataManager.register();
    }

    @Override
    public void doProcess() {
        try {
            YamlPropertiesFactoryBean yamlMapFactoryBean = new YamlPropertiesFactoryBean(); //可以加载多个yml文件
            yamlMapFactoryBean.setResources(new ClassPathResource("application.yml"));
            Properties properties = yamlMapFactoryBean.getObject(); //获取yml里的参数
            int port = Integer.valueOf(properties.getProperty(RPC_SERVER_NETTY_PORT));
            this.nettyServer = new NettyServer(port, serializeProtocol);
            nettyServer.doStart();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("start netty server error,message is "+e.getMessage());
        }
    }
}
